package tech.heptagram.staff.cas.controller.view;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Objects;

import javax.annotation.Resource;

import tech.heptagram.core.common.rest.ResponseResult;
import tech.heptagram.staff.cas.common.AssertUtils;
import tech.heptagram.staff.cas.common.CurrentUserUtil;
import tech.heptagram.staff.cas.domain.info.RolePermissionReq;
import tech.heptagram.staff.cas.domain.po.Role;
import tech.heptagram.staff.cas.service.staff.CasRoleService;

/**
 * @author zilaiye
 * @date 2017/12/8
 */
@RestController
@RequestMapping("/api/view/sys/role")
public class CasRoleApiController {

    @Resource
    private CasRoleService casRoleService;

    /**
     * 查询所有角色列表
     */
    @PostMapping("/listall")
    public ResponseResult<List<Role>> allRoleList() {
        List<Role> allRoles = casRoleService.findAll();
        return new ResponseResult<>(allRoles);
    }

    @PostMapping("/ids/{staffCode}")
    public ResponseResult<List<Integer>> findRoleIdsByStaffCode(@PathVariable String staffCode){
        List<Integer> roleIds = casRoleService.findRoleIdsByStaffCode(staffCode);
        return new ResponseResult<>(roleIds);
    }

    /**
     * 查询指定ID的角色信息
     */
    @PostMapping("/detail/{id}")
    public ResponseResult<Role> roleDetails(@PathVariable Integer id) {
        Role role = casRoleService.findById(id);
        return new ResponseResult<>(role);
    }

    /**
     * 保存角色信息
     *
     * @param role
     * @return
     */
    @PostMapping("/save")
    public ResponseResult<Boolean> saveRole(@RequestBody Role role) {
        AssertUtils.notNull(role, "要保存的角色为Null");
        role.setModifiedBy(CurrentUserUtil.getCurrentUser().getTrueName());
        if (Objects.nonNull(role.getId())) {
            casRoleService.updateRole(role);
        } else {
            role.setCreatedBy(CurrentUserUtil.getCurrentUser().getTrueName());
            casRoleService.saveRole(role);
        }
        return new ResponseResult<>(true);
    }

    /**
     * 删除角色
     *
     * @param id
     * @return
     */
    @PostMapping("/delete/{id}")
    public ResponseResult<Boolean> removeRole(@PathVariable Integer id) {
        casRoleService.deleteById(id, CurrentUserUtil.getCurrentUser().getTrueName());
        return new ResponseResult<>(true);
    }

    /**
     * 设置角色权限
     *
     * @param req
     * @return
     */
    @PostMapping("/permission/save")
    public ResponseResult<Integer> saveRoleMenu(@RequestBody RolePermissionReq req) {
        req.setCreatedBy(CurrentUserUtil.getCurrentUser().getTrueName());
        Integer num = casRoleService.saveRolePermission(req);
        return new ResponseResult<>(num);
    }
}
